<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<!--{include file='comm/header.tpl'}-->
    <!--{include file='comm/comm_cal.tpl'}-->
    <!--{if $operFlg == 1}-->
    <title>超值选购添加</title>
    <!--{else}-->
    <title>超值选购编辑</title>
    <!--{/if}-->
<style>
	html{
		overflow-y:scroll;
		overflow:-moz-scrollbars-vertical;
	}
</style>
</head>
<body>
	<div style="width:100%">
		
		<div class="items clearfix">
			<h2 style="" class="tal">
				<!--{if $operFlg == 1}-->
			    	超值选购添加
			    <!--{else}-->
			    	超值选购编辑
			    <!--{/if}-->
			</h2>
			
			<div class="items2">
				<!--{if isset($error_msg)}-->
	            
				<div class="comm-box">
	                <div style="position:relative;color: red;">
	                    <!--{$error_msg}-->
	                </div>
	            </div>
				
	            <!--{else}-->
				<div>
					<form id="addForm" name="addForm" onsubmit="return false;">
					
						<div style="padding-bottom:10px;float:left;" class="allTextTime">
							<div class="input-group input-group-lg">
								<span class="input-group-addon">活动名称：</span>
								<input type="text" style="padding-left:8px;" class="form-control hasDatepicker" id="goodsChoiceName" name="goodsChoiceName" placeholder="请输入活动名称【必填项】" value="<!--{$selectionInfo.goodsChoiceName|default:''}-->">
								<input type="hidden" id="goodsChoiceID" name="goodsChoiceID" value="<!--{$selectionInfo.goodsChoiceID|default:''}-->">
								<input type="hidden" id="choice_type" name="choice_type" value="<!--{$choice_type|default:''}-->">
							</div>
							
							<div class="input-group input-group-lg">
				                <span class="input-group-addon">所属分类：</span>
				                <span class="input-group-radio" style="padding-left:10px;">
				                	<select id="itemID" name="itemID" style="width:180px;">
										<option value="">请选择</option>
										
											<!--{foreach from=$item item=itemList}-->
												<option value="<!--{$itemList->itemID}-->" <!--{if $selectionInfo.itemID eq $itemList->itemID}-->selected="selected"<!--{/if}-->><!--{$itemList->itemName}--></option>
											<!--{/foreach}-->
										
									</select>
				                </span>
				            </div>
				            
				            <div class="input-group input-group-lg">
				                <span class="input-group-addon">活动价格：</span>
				                <input type="text" class="form-control" name="goodsChoicePrice" id="goodsChoicePrice" placeholder="请输入活动价格【必填项】" value="<!--{$selectionInfo.goodsChoicePrice|default:''}-->" style="padding-left:10px;">
				            </div>
				            
				            <div class="input-group input-group-lg">
				                <span class="input-group-addon">选购数量：</span>
				                <input type="text" class="form-control" name="goodsCount" id="goodsCount" placeholder="请输入选购数量【必填项】" value="<!--{$selectionInfo.goodsCount|default:''}-->" style="padding-left:10px;">
				            </div>
				            
				            <div class="input-group input-group-lg">
				                <span class="input-group-addon">活动积分：</span>
				                <input type="text" class="form-control" name="points" id="points" placeholder="请输入活动积分【必填项】" value="<!--{$selectionInfo.points|default:''}-->" style="padding-left:10px;">
				            </div>
				            
				            <div class="input-group input-group-lg">
				                <span class="input-group-addon">有效日期：</span>
				                <span class="input-group-radio" style="padding-left:10px;">
				                    <div>
				                        <input type="text" id="useStartDate" readonly="" name="useStartDate" value="<!--{$selectionInfo.useStartDate|default:''}-->" style="width:180px;">
				                        ～
				                        <input type="text" id="useEndDate" readonly="" name="useEndDate" value="<!--{$selectionInfo.useEndDate|default:''}-->" style="width:180px;">
				                    </div>
				                </span>
				            </div>
				            
						</div>
						
						<div style="float:right;height:290px;width:240px;margin:8px 18px 0px 0px;" class="goodsImg">
							<div id="pic_div" style="height:240px;width:240px;border:1px solid #E0E0E0;">
					            <!--{if isset($selectionInfo) && $selectionInfo.thumbpic != ''}-->
									<img src="<!--{$selectionInfo.thumbpic}-->" id="activityPic" name="activityPic" style="width:130px;height:160px;">
								<!--{/if}-->
							</div>
							<div style="margin-top:12px;text-align:center;">
								<input type="button" class="btn" id="uploadPic" name="uploadPic" value="上传展示图片">
								<input type="hidden" id="oldPicName" name="oldPicName" value="<!--{$selectionInfo.thumbpic|default:''}-->">
								<input type="hidden" id="picName" name="picName" value="">
							</div>
						</div>
					</form>
				</div>
				<table class="s" id="selection_goods"  style="margin-top: 20px;">
                    <tr>
                        <th width="18%">商家编码</th>
                        <th width="*">商品名称</th>
                        <th width="15%">销售价</th>
                        <!--<th width="15%"> 商品数量</th>-->
                        <th width="15%">操作</th>
                    </tr>
                    <!--{if isset($selectionGoodsInfo)}-->
                        <!--{foreach from=$selectionGoodsInfo  item=goods}-->
                        <tr id="tr_<!--{$goods->product_code}-->">
                            <td width="18%" style="text-align: center;"><!--{$goods->product_code}--></td>
                            <td width="*"><!--{$goods->goodsName}--></td>
                            <td width="15%"><!--{$goods->salePrice}--></td>
                            <!--<td width="15%"><!- -{$goods->goodsCount}- -></td>-->
                            <td width="15%" style="text-align: center;"><a href="javascript:void(0); " onclick="source.del('<!--{$goods->product_code}-->');" >删除</a></td>
                        </tr>
                        <!--{/foreach}-->
                    <!--{/if}-->
                    <tr id="nextLine">
                        <td width="18%" style="text-align: center;"><input type="text" id="product_code" style='width: 100px;height:20px;' ></td>
                        <td width="*"></td>
                        <td width="15%"></td>
                        <!--<td width="15%"></td>-->
                        <td width="15%"></td>
                    </tr>
				</table>
				<!--{/if}-->
			</div>
		</div>
		
		<div class="bottom_fixbox">
			<div class="rectbox tac">
				<input type="hidden" value="" id="dataCache" name="dataCache"/>
				<input type="button" class="btn" onclick="E.refresh();" value="重置">
	        	<!--{if $operFlg == 1}-->
	        		<input type="button" class="btn" onclick="source.edit();" value="添加超值选购">
				<!--{else if $operFlg == 2}-->
					<input type="button" class="btn" onclick="source.edit();" value="修改超值选购">
				<!--{/if}-->
				<input type="button" class="btn" onclick="E.closeWindows();" value="关闭">
	        </div>
		</div>
	</div>
	<script>
		//operFlg
		var operFlg = '<!--{$operFlg}-->';

        //添加的商品数组
        var goods_array = { };
		
		//数组索引值
		var index = 0;
		
		$("#product_code").keypress(function (event){
            if (event.keyCode == 13){
                //阻止元素默认行为（提交表单）
                event.preventDefault();
                var product_code = $.trim($('#product_code').val());
                //是否空值
                if (E.isEmpty(product_code)){
                    E.alert('请输入商品编号');
                    return false;
                }
                //是否已有该商品
                if(!$.isEmptyObject(goods_array[product_code])){
                    E.alert('该商品已存在，请勿重复输入');
                    return;
                }

                add_goods(product_code);
            }
        });
		
		//根据product_code查询商品方法
		function add_goods (product_code){
			$.ajax({
				type: "POST",
				url: "/invokingAjax-backend/promotion/selection.ajax?operFlg=5",
				dataType: "JSON",
				data:{'product_code': product_code},
				success: function(result_obj){
					if (result_obj.code != 200) {
						return E.alert(result_obj.message);
					}

                    addLine(result_obj.message);

				}
			});
		}

        //根据商品编号查询成功后，添加一行
        function addLine (data){
                console.log(data);
                var html = "<tr id='tr_"+data.product_code+"'>";
                    html += "<td width='18%' style='text-align: center;'>"+data.product_code+"</td>";
                    html += "<td width='*'>"+data.goodsName+"</td>";
                    html += "<td width='15%'>"+data.salePrice+"</td>";
                    //html += "<td width='15%'>"+data.goodsCount+"</td>";
                    html += "<td width='15%' style='text-align: center;'><a href='javascript:void(0);' onclick=\"source.del('"+data.product_code+"');\" >删除</a></td>";
                    html += "</tr>";
                //页面添加一行
                $("#nextLine").before(html);
                //清除商品编号输入框内的值
                $("#product_code").val('');
                //数据保存进商品数组
               goods_array[data.product_code] = data;
        }
		
		//页面初始化时加载
		$(document).ready(function(){
			
			//上传图片
			$("#uploadPic").click(function (){
				window.open('/quanliadmin/app/uploads/imageUpload.php?uploadPara=16','上传','height=50, width=600, top=280,left=300,toolbar=no, menubar=no, scrollbars=no,resizable=no,location=no, status=no');
			});
			
			//编辑页自动接收后端传入的数据并放入dataCache中
			if (operFlg == 2){
				//接受套装商品并放入dataCache中
				var selectionGoodsInfo = '<!--{$selectionGoodsInfo|default:''}-->';
				selectionGoodsInfo = eval("("+selectionGoodsInfo+")");
				
				var selectionGoodsIDObj = {};
				
				$.each(selectionGoodsInfo, function(k,v){
					v[0] = '<a href="javascript:void(0);" onclick="source.change('+k+')">修改</a>';
					selectionGoodsIDObj[k] = v;
					index = Number(k) + 1;
				});
				
				$("#dataCache").data("selectionGoodsIDObj",selectionGoodsIDObj);
				
				//加入空白编辑行
				add_edit_tr();
			}
			//选择套装名称输入框
			$('#goodsChoiceName').select();
		});
		
		//活动名输入框键盘事件
		$('#goodsChoiceName').keypress(function(event){
			if (event.keyCode == 13){
				//阻止元素默认行为（提交表单）
				event.preventDefault();
				goodsChoiceName = $('#goodsChoiceName').val();
				if (goodsChoiceName == ''){
					E.alert('请输入活动名称');
					return false;
				}
				//选择套装价格输入框
				$('#goodsChoicePrice').select();
			}
		});
		
		//活动价格输入框键盘事件
		$('#goodsChoicePrice').keypress(function(event){
			if (event.keyCode == 13){
				//阻止元素默认行为（提交表单）
				event.preventDefault();
				goodsChoicePrice = $('#goodsChoicePrice').val();
				if (goodsChoicePrice == '' || !E.isMoney(goodsChoicePrice)){
					E.alert('未输入格式正确的活动价格');
					return false;
				}
				//选择选购数量输入框
				$('#goodsCount').select();
			}
		});
		
		//选购数量输入框键盘事件
		$('#goodsCount').keypress(function(event){
			if (event.keyCode == 13){
				//阻止元素默认行为（提交表单）
				event.preventDefault();
				goodsCount = $('#goodsCount').val();
				if (goodsCount == '' || !E.isInt(goodsCount) || goodsCount == 0){
					E.alert('选购数量为大于0的整数');
					return false;
				}
				//选择活动积分输入框
				$('#points').select();
			}
		});
		
		//活动积分输入框键盘事件
		$('#points').keypress(function(event){
			if (event.keyCode == 13){
				//阻止元素默认行为（提交表单）
				event.preventDefault();
				points = $('#points').val();
				if (points == ''){
					$('#points').val(0);
				}
				if (!E.isInt(points) || points == ''){
					E.alert('活动积分为大于等于0的整数');
					return false;
				}
				add_edit_tr();
			}
		});
		

		var source = {
			
			edit: function(){
			
				//取出dataCache
				var	selectionGoodsIDObj = goods_array;
				
				var checkArr = new Array();
				
				$.each(selectionGoodsIDObj, function(k,v){
					checkArr.push(k);
				});
				
				var goodsChoiceName = E.trim($('#goodsChoiceName').val());
				var goodsChoiceID = E.trim($('#goodsChoiceID').val());
				var itemID = $('#itemID').val();
				var choice_type = E.trim($('#choice_type').val());
				var goodsChoicePrice = E.trim($('#goodsChoicePrice').val());
				var goodsCount = E.trim($('#goodsCount').val());
				var points = E.trim($('#points').val());
				var useStartDate = E.trim($('#useStartDate').val());
				var useEndDate = E.trim($('#useEndDate').val());
				var picName = $('#picName').val();
				var oldPicName = $('#oldPicName').val();
				var error_msg = '';
				if (goodsChoiceName == ''){
					error_msg += '活动名称不能为空<br/>';
				}
				if (itemID == ''){
					error_msg += '所属分类不能为空<br/>';
				}
				if (goodsChoicePrice == ''){
					error_msg += '活动价格不能为空<br/>';
				}
				if (goodsCount == ''){
					error_msg += '选购数量不能为空<br/>';
				}
				if (!E.isInt(points) || points == ''){
					error_msg += '活动积分为大于等于0的整数<br/>';
				}
				if (picName == '' && oldPicName == ''){
					error_msg += '展示图片不能为空<br/>';
				}
				if (useStartDate == ''){
					error_msg += '开始时间不能为空<br/>';
				}
				if (useEndDate == ''){
					error_msg += '结束时间不能为空<br/>';
				}
				if (useStartDate > useEndDate){
					error_msg += '开始时间不能大于结束时间<br/>';
				}
				if (useEndDate < E.currentDate()){
					error_msg += '有效期结束时间不能小于当前时间<br/>';
				}
				/************************必须有其他套装商品********************************/
				if (checkArr.length <= 1){
					error_msg += '请添加至少2件商品<br/>';
				}
				/************************必须有其他套装商品********************************/
				if (error_msg != ''){
					return E.alert(error_msg);
				}
				var addForm = E.getFormValues('addForm');
				$.ajax({
					type: "POST",
					<!--{if $operFlg == 1}-->
	                url: "/invokingAjax-backend/promotion/selection.ajax?operFlg=2",
					<!--{else}-->
					url: "/invokingAjax-backend/promotion/selection.ajax?operFlg=3",
					<!--{/if}-->
	                dataType: "JSON",
					data: {'mainInfo': addForm, 'selectionInfo': selectionGoodsIDObj},
					success: function( result_obj ) {
	                    if (result_obj.code == 200) {
							E.opener("source.load");
							if (operFlg == 1){
								E.alert(result_obj.message,  2, "E.refresh");
							}else{
								E.alert(result_obj.message,  2, "E.closeWindows");
							}
	                    } else {
	                        E.alert(result_obj.message);
	                    }
	                }
				});
			},
			pubIndexArr: new Array(),

			//删除
			del: function(product_code){
                this.product_code = product_code;
                E.confirm("是否确认删除该商品？","source.delConfirm");
			},
            //删除确认
            delConfirm : function (){
                //删除页面行
                $("#tr_"+this.product_code).remove();
                //删除js数据
                delete goods_array[this.product_code];
            },

			change: function (indexFlg){
				var product_code = '';
				var goodsName = '';
				var salePrice = '';
				var goodsCount = '';
				
				//取出dataCache
				var	selectionGoodsIDObj = $("#dataCache").data("selectionGoodsIDObj");
				//清空表格数组
				table_obj.rows = new Array();
				//循环表格数组
				$.each(selectionGoodsIDObj,function(k,v){
					if (k == indexFlg){
						//插入编辑行
						table_obj.rows.push(edit_tr_obj);
						
						//给中间变量product_code、goodsName、salePrice、goodsCount赋值
						product_code = v[1];
						goodsName = v[2];
						salePrice = v[3];
						goodsCount = v[4];
						
//						if (indexFlg != 0){
//							publicGoodsObj = groupGoodsIDObj[k];
//							publicIndex = k;
//						}
					}else{
						table_obj.rows.push({'id':k,'cell':v});
					}
				});
				
				//取出dataCache
//				$("#dataCache").data("groupGoodsObj",groupGoodsIDObj);
				//重绘表格
				$("#flex").flexAddData(table_obj);
				
				//将当前索引值传给全局变量checkIndex
				checkIndex = indexFlg;
				
				$("#product_code").val(product_code);
				$("#goodsName").html(goodsName);
				$("#salePrice").html(salePrice);
				$("#goodsCount").html(goodsCount);
			}
		};
		
		//给页面赋上新上传的图片（团购主图片）
		function getUploadFileName(upload_fileName){
			$('#pic_div').html();
			var img_src = "/quanliadmin/docroot/images/promotion/"+upload_fileName+"?code=" + Math.ceil(Math.random() * 10000);
			var img_html = '<img src="'+img_src+'" id="activityPic" name="activityPic" style="width:130px;height:160px;">';
			$('#pic_div').html(img_html);
			$("#picName").val(upload_fileName);
		}

        <!--{if isset($selectionGoodsInfo)}-->
        <!--{foreach from=$selectionGoodsInfo  item=goods}-->
            goods_array["<!--{$goods->product_code}-->"] = {
            goodsID : "<!--{$goods->goodsID}-->",
            postID : "<!--{$goods->postID}-->",
            mainPostID : "<!--{$goods->mainPostID}-->",
            goodsName : "<!--{$goods->goodsName}-->",
            goodsSpec : "<!--{$goods->goodsSpec}-->",
            goodsCount : "<!--{$goods->goodsCount}-->",
            product_code : "<!--{$goods->product_code}-->"
        };
        <!--{/foreach}-->
        <!--{/if}-->

		$('#useStartDate').datetimepicker({timeFormat:'HH:mm:ss',showHour: true,showMinute: true,showSecond: true});
		$('#useEndDate').datetimepicker({timeFormat:'HH:mm:ss',showHour: true,showMinute: true,showSecond: true});

	</script>
</body>
</html>